package com.clsz.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.clsz.bean.bo.SiteChooseBo;
import com.clsz.bean.po.Orders;
import com.clsz.mapper.OrderMapper;
import com.clsz.service.SiteService;
import com.clsz.utils.RedisUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SiteServiceImpl implements SiteService {
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RedissonClient redissonClient;

    @Override
    public boolean chooseSite(SiteChooseBo siteChooseBo, String authrization) {
        //1判断该作为是否被冻结】
        String key = "Site-Frozen-" + JSON.toJSONString(siteChooseBo);
        if (redisUtils.hasKey(key)) {
            //已冻结
            return false;
        }
        //2判断MySQL中是否有订单
        LambdaQueryWrapper<Orders> ordersWrapper = Wrappers.lambdaQuery();
        ordersWrapper.eq(Orders::getOrderWtId, siteChooseBo.getWatchTimesId());
        ordersWrapper.like(Orders::getOrderSites, "%"+JSON.toJSONString(siteChooseBo.getSiteBo())+"%");
        List<Orders> orders = orderMapper.selectList(ordersWrapper);
        if (orders.size() > 0) {
            return false;
        }
        //3争夺分布式锁
        RLock lock = redissonClient.getLock("lock-" + key);
        lock.lock();
        //4.生成冻结信息
        boolean result = redisUtils.set(key, authrization, 60 * 5);
        lock.unlock();
        return result;
    }
}
